package com.mbinno.android.comm.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Base64;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.security.KeyStoreException;

public class EncryptedSharedPreferences {

    private static final String KEY_ALIAS_DEF = "key_alias_mobile_inno";
    private static final String SP_NAME_DEF = "encrypted_shared_preferences";

    private final Context mContext;

    private final String mKeyAlias;

    private SharedPreferences mSP;

    public EncryptedSharedPreferences(Context mContext) {
        this(mContext, KEY_ALIAS_DEF, SP_NAME_DEF);
    }

    public EncryptedSharedPreferences(Context mContext, String mKeyAlias, String spName) {
        this.mContext = mContext;
        this.mKeyAlias = mKeyAlias;
        initKeyStore();
        initSharedPreferences(spName);
    }

    private void initKeyStore() {
        try {
            if (!KeyStoreHelper.isKeyPairGenerated(mKeyAlias)) {
                KeyStoreHelper.generateKeyPair(mContext, mKeyAlias);
            }
        } catch (Exception ignored) {

        }
    }

    private void initSharedPreferences(String spName) {
        mSP = mContext.getSharedPreferences(spName, Context.MODE_PRIVATE);
    }


    public @NonNull String getString(String key) throws KeyStoreException {
        return getString(key, "");
    }

    private @NonNull String getString(String key, String defValue) throws KeyStoreException {
        String value = mSP.getString(key, defValue);
        if (TextUtils.isEmpty(value))
            return defValue;

        byte[] decode = Base64.decode(value, Base64.NO_WRAP);
        return new String(KeyStoreHelper.decryptData(mKeyAlias, decode));

    }

    public void setValue(@NonNull String key, @Nullable String value) {
        SharedPreferences.Editor edit = mSP.edit();
        if (!TextUtils.isEmpty(value)) {
            try {
                value = Base64.encodeToString(KeyStoreHelper.encryptData(mKeyAlias, value), Base64.NO_WRAP);
            } catch (Exception ignored) {
            }
        }
        edit.putString(key, value);
        edit.apply();
    }


}
